<template>
  <div>
    <el-dialog
      :visible="showDialog"
      v-bind="$attrs"
      :title="title"
      v-on="$listeners"
      @open="onOpen"
      @close="onClose"
    >
      <el-form
        ref="deptForm"
        :model="formData"
        :rules="rules"
        size="medium"
        label-width="120px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入部门名称"
            clearable
            :style="{ width: '80%' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input
            v-model="formData.code"
            placeholder="请输入部门编码"
            clearable
            :style="{ width: '80%' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-select
            v-model="formData.manager"
            placeholder="请选择负责人"
            clearable
            :style="{ width: '80%' }"
            @focus="getEmployeeSimple"
          >
            <el-option
              v-for="(item, index) in peoples"
              :key="index"
              :label="item.username"
              :value="item.username"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input
            v-model="formData.introduce"
            type="textarea"
            placeholder="请输入部门介绍"
            :autosize="{ minRows: 1, maxRows: 3 }"
            :style="{ width: '80%' }"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-row slot="footer" type="flex" justify="center">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="btnOk">确定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getDepartments, addDepartment, updateDepartments, getDepartDetail } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  name: 'AddDept',
  components: {},
  inheritAttrs: false,
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    treeNode: { // 新增-父部门  编辑-本部门
      type: Object,
      required: true
    }
  },
  data() {
    const checkName = async(rule, value, callback) => {
      // 兄弟部门中禁止出现重复部门
      // 方式1 不发请求，得到兄弟部门
      // const brothers = this.treeNode.children
      // 方式2 发请求，得到所有部门，再匹配当前部门的所有子部门
      const { depts } = await getDepartments() // 获取全部部门

      let brothers
      if (this.formData.id) {
        // 编辑
        brothers = depts.filter(t => t.pid === this.treeNode.pid && t.id !== this.treeNode.id) // 排除自己，得到兄弟
      } else {
        // 新增
        brothers = depts.filter(t => t.pid === this.treeNode.id) // 得到兄弟
      }

      // 在兄弟部门中存不存在有一个同名的部门
      const isExist = brothers.some(t => t.name === value)
      if (isExist) {
        callback('存在同名的兄弟部门') // 不符合规则
      } else {
        callback() // 放行
      }
    }
    // 部门编码在整个模块中都不重复
    const checkCode = async(rule, value, callback) => {
      // value就是要校验的值，callback提示信息的回调函数
      const { depts } = await getDepartments() // 获取全部部门
      let isExist
      if (this.formData.id) {
        // 编辑
        isExist = depts.filter(t => t.id !== this.treeNode.id).some(t => t.code === value)
      } else {
        // 新增
        isExist = depts.some(t => t.code === value)
      }
      if (isExist) {
        callback('已经存在同编号部门')
      } else {
        callback()
      }
    }
    return {
      // 表单数据
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      peoples: [], // 定义简单员工数组
      rules: {
        name: [{
          required: true,
          message: '请输入部门名称',
          trigger: 'blur'
        }, {
          min: 1,
          max: 20,
          message: '限制1~20',
          trigger: 'blur'
        }, {
          trigger: 'blur',
          validator: checkName
        }],
        code: [{
          required: true,
          message: '请输入部门编码',
          trigger: 'blur'
        }, {
          min: 1,
          max: 20,
          message: '限制1~20',
          trigger: 'blur'
        }, {
          trigger: 'blur',
          validator: checkCode
        }],
        manager: [{
          message: '请选择负责人',
          trigger: 'change'
        }],
        introduce: [{
          required: true,
          message: '请输入部门介绍',
          trigger: 'blur'
        }, {
          min: 1,
          max: 300,
          message: '限制1~300',
          trigger: 'blur'
        }]
      },
      managerOptions: [{
        'label': '选项一',
        'value': 1
      }, {
        'label': '选项二',
        'value': 2
      }]

    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑部门' : '新增部门'
    }
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    onOpen() {},
    onClose() {
      this.close()
    },
    close() {
      // 重置数据
      // 方法一
      // this.formData = {
      //   name: '',
      //   code: '',
      //   manager: '',
      //   introduce: ''
      // }
      // 方法二
      // this.formData = this.$options.data().formData
      // 重置表单
      this.$refs.deptForm.resetFields()
      this.$emit('update:showDialog', false)
      // this.$parent.showDialog = false
    },
    btnOk() {
      this.$refs['deptForm'].validate(async isOk => {
        if (!isOk) return
        // 发请求
        if (this.formData.id) {
          // 有id就是编辑
          await updateDepartments(this.formData)
        } else {
          // 没id就是新增
          // 表单校验通过
          // 将父节点ID设置为新节点的pid
          await addDepartment({ ...this.formData, pid: this.treeNode.id }) // 调用新增接口 添加父部门的id
        }
        // 通知父组件重新获取组织架构
        this.$emit('addDepts')
        this.close()
      })
    },
    // 获取员工简单列表
    async getEmployeeSimple() {
      this.peoples = await getEmployeeSimple()
    },
    // 获取部门详细列表
    async getDepartDetail(id) {
      const formData = await getDepartDetail(id)
      this.formData = formData
    }
  }
}

</script>
<style>
</style>
